// intended for use on cd review posts with the rating scale image
// only called if rating custom field is unavailable

// searches for filenames of rating images (ex: Fresh1-300x21.jpg)
// and parses the filename to figure out the rating - then we can
// edit and manipulate the value;

// also sends an ajax request to /ajax/update_article_rating.php, 
// which updates the custom meta data of a post with the fetched
// rating - allows us to display ratings in category view etc.

// on page load, or won't run correctly
$(function() {

	var post_id = $('.post').attr('id');
	var ajax_url = "http://tastemakersmag.com/wp-content/themes/tays-t/ajax/update_article_rating.php";
	
	$('#content img').each(function() { 
	    var url_str = $(this).attr('src');
	    var filename_str = url_str.replace(/^.*\//, '');
	    	    
	    var tasty = filename_str.search(/tasty/i);
	    var fresh = filename_str.search(/fresh/i);
	    var edible = filename_str.search(/edible/i);
	    var stale = filename_str.search(/stale/i);
	    var moldy = filename_str.search(/moldy/i);
	    
	    // search() returns -1 for not found. when it finds a match, it returns the
	    // starting place in the string (ex: "test one test".search('one') would return 5)
	    if (Math.max(tasty, fresh, edible, stale, moldy) > -1) {	    	
	    	$(this).remove();
	    	
	    	if (tasty > -1) {
	    		$('#content').prepend('<p id="rating">Moldy | Stale | Edible | Fresh | <em>Tasty!</em></p>');
				$.ajax({ type: "POST", url: ajax_url, data: "post_id="+post_id+"&rating=tasty" });
	    	}
	    	if (fresh > -1) {
	    		$('#content').prepend('<p id="rating">Moldy | Stale | Edible | <em>Fresh</em> | Tasty!</p>');
				$.ajax({ type: "POST", url: ajax_url, data: "post_id="+post_id+"&rating=fresh" });
	    	}
	    	if (edible > -1) {
	    		$('#content').prepend('<p id="rating">Moldy | Stale | <em>Edible</em> | Fresh | Tasty!</p>');
				$.ajax({ type: "POST", url: ajax_url, data: "post_id="+post_id+"&rating=edible" });
	    	}
	    	if (stale > -1) {
	    		$('#content').prepend('<p id="rating">Moldy | <em>Stale</em> | Edible | Fresh | Tasty!</p>');
				$.ajax({ type: "POST", url: ajax_url, data: "post_id="+post_id+"&rating=stale" });
	    	}
	    	if (moldy > -1) {
	    		$('#content').prepend('<p id="rating"><em>Moldy</em> | Stale | Edible | Fresh | Tasty!</p>');
				$.ajax({ type: "POST", url: ajax_url, data: "post_id="+post_id+"&rating=moldy" });
	    	}
	    }
	});
});